package com.admin.service;

import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.admin.bean.CompanyBean;
import com.admin.bean.MobileTypeBean;
import com.admin.dao.CompanyDao;
import com.admin.dao.MobileProductDao;
import com.admin.dao.MobileTypeDao;

@Service("companyService")
public class CompanyService {

	@Autowired private CompanyDao companyDao;
	@Autowired private MobileTypeDao mobileTypeDao;
	@Autowired private MobileProductDao mobileProductDao;
	
	/**
	 * 获取公司总数
	 * @return
	 */
	public int findCount(){
		return companyDao.findCount();
	}
	
	public int findCount(String condition){
		return companyDao.findCount(condition);
	}
	
	/**
	 * 分页查询公司
	 * @param start
	 * @param pageSize
	 * @return
	 */
	public List<CompanyBean> findList(int start,int pageSize){
		try {
			return companyDao.findList(start, pageSize);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	public List<CompanyBean> findList(String condition,int start,int pageSize){
		try {
			return companyDao.findList(condition,start, pageSize);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 根据公司ID查询公司信息
	 * @param companyId
	 * @return
	 */
	public CompanyBean findCompanyById(int companyId){
		try {
			return companyDao.findCompanyById(companyId);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 添加新的 公司
	 * @param company
	 * @return
	 */
	public int insertCompany(CompanyBean company){
		return companyDao.insertCompany(company);
	}
	
	/**
	 * 修改公司信息
	 * @param company
	 * @return
	 */
	public int updateCompany(CompanyBean company){
		return companyDao.updateCompany(company);
	}
	
	/**
	 * 删除公司信息
	 * @param companyId
	 * @return
	 */
	public int delCompany(int companyId){
		List<MobileTypeBean> mobileTypeList;
		try {
			mobileTypeList= mobileTypeDao.findMobileTypeByCompanyId(companyId);
		} catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
		
		if(mobileTypeList!=null && mobileTypeList.size()>0){
			for (MobileTypeBean mobileTypeBean : mobileTypeList) {
				int mobileTypeId = mobileTypeBean.getMobileTypeId();
				mobileProductDao.delBymobileTypeId(mobileTypeId);
				mobileTypeDao.delMobileTypeById(mobileTypeId);
			}
			companyDao.delCompany(companyId);
			return 1;
		}else{
			companyDao.delCompany(companyId);
			return 1;
		}
	}
	
	/**
	 * 查询所有的公司
	 * @return
	 */
	public List<CompanyBean> findAllList() {
		try {
			return companyDao.findAllList();
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
}
